import { Toast } from "antd-mobile";
import axios, { RawAxiosRequestHeaders } from "axios";

const BASEURL = process.env.NODE_ENV === "delelopment" ? "/api" : "/api";

interface IRsponseData {
  data: any;
  message: string;
  errCode: string;
}

export default function (
  url: string,
  data: object = {},
  headers: RawAxiosRequestHeaders = {},
  method: "POST" | "GET" = "POST"
) {
  return new Promise<IRsponseData>((resolve, reject) => {
    headers = Object.assign({}, headers, {
      "x-auth-token": localStorage.getItem("token"),
    });

    axios({
      url: BASEURL + url,
      data: method === "POST" ? data : null,
      params: method === "GET" ? data : null,
      headers: headers,
      method: method,
      responseType: "json",
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        console.log(err.response.data.message);
        if (err.errCode !== 0) {
          Toast.show({
            icon: "fail",
            content: err.response.data.message,
          });
        }
        reject(err);
      });
  });
}
